<template>
	<view class="content">
		<view class="top">
			<view class="text">
				<h1 class="title">蓝牙自动开关配置</h1>
				<text class="title-en">Automated configuration</text>
				<image src="@/static/images/juxing.png" />
			</view>

			<image src="@/static/images/chahua.png" class="position-img" />
		</view>
		<view class="scancode-box">
			<view class="scancode">
				<h2 class="scancodetitle">STEP 01：扫码获取产品信息</h2>
				<view class="scan-input">
					<input class="uni-input" :value="scanValue" placeholder="暂无产品信息" disabled />
					<uni-icons class="scan-icon" type="scan" @click="handleScan"></uni-icons>
				</view>
			</view>
		</view>
		<view class="time-box">
			<view class="setting-box">
				<h2 class="time-title">STEP 01：扫码获取产品信息</h2>
				<view class="setting-time">
					<uni-forms ref="valiForm" :rules="rules" :modelValue="timeFormData">
						<uni-forms-item label="通电时间:" name="name">
							<picker mode="time" :value="timeFormData.powerOnTime" @change="powerOnTimeChange">
								<view class="uni-input">{{timeFormData.powerOnTime}}</view>
							</picker>
						</uni-forms-item>
						<uni-forms-item label="断电时间:" name="age">
							<picker mode="time" :value="timeFormData.powerOutageTime" @change="powerOutageTimeChange">
								<view class="uni-input">{{timeFormData.powerOutageTime}}</view>
							</picker>
						</uni-forms-item>

					</uni-forms>
					<view class="submit-btn" @click="submit(timeFormData)">
						<image src="@/static/images/time.png" />
					</view>
				</view>
			</view>
		</view>
		<view class="history-box">
			<view class="setting-history">
				<view class="history-title">
					<view class="min-title">
						历史配置
					</view>
					<view class="click">
						点击选择
					</view>
				</view>
				<view class="history-list" v-if="historyList.length>0">
					<ul>
						<li v-for="(item,index) in historyList" :key="index" @click="submit(item)">
							<span class="sort">0{{index+1}}</span>
							<view class="bluetooth-item">
								<image src="@/static/images/bluetooth.png" mode=""></image>
								<text>通电时间：{{item.powerOnTime}} | 断电时间：{{item.powerOutageTime}}</text>
							</view>
						</li>
					</ul>
				</view>
				<view class="empty" v-else>
					<image src="@/static/images/empty.png" mode=""></image>
				</view>
			</view>
		</view>

		<uni-popup ref="alertDialog">
			<view class="popup-content">
				<img class="img" src="@/static/images/confirm-img.png" alt="">
				<text class="text">蓝牙配置</text>
				<text class="text">设置成功</text>
				<view class="confirm-btn" @click="confirmBtn">
					确认
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {queryConfig,addConfig} from '@/api/index.js'
	import {
		ab2hex,
		hexCharCodeToStr,
		stringTobuffer
	} from '@/utils/index.js'
	export default {
		data() {
			return {
				scanValue: "", //码值
				msgType: "",
				timeFormData: {
					powerOnTime: "07:00",
					powerOutageTime: "19:00"
				},
				historyList: [{
						powerOnTime: '07:00',
						powerOutageTime: '19:00',
					},
					{
						powerOnTime: '08:00',
						powerOutageTime: '20:00',
					}, {
						powerOnTime: '08:00',
						powerOutageTime: '20:00',
					}, {
						powerOnTime: '08:00',
						powerOutageTime: '20:00',
					}, {
						powerOnTime: '08:00',
						powerOutageTime: '20:00',
					},
				],
				resdic: [], //外部设备
				deviceIdStr: "", //获取的deviceId
				serviceIdStr: "", //获取的serviceId
			}
		},
		onLoad() {
			this.openBluetoothAdapter()
			// queryConfig({"serialNumber":"88888888"}).then(res=>{
			// 	console.log(res.data)
			// 	this.historyList=res.data
			// })
		},
		onHide() {
			this.closeBluetooth()
		},
		methods: {
			powerOnTimeChange: function(e) {
				this.timeFormData.powerOnTime = e.detail.value
			},
			powerOutageTimeChange: function(e) {
				this.timeFormData.powerOutageTime = e.detail.value
			},
			//扫码获取值
			handleScan() {
				// 允许从相机和相册扫码
				uni.scanCode({
					success: res => {
						// console.log('条码类型：' + res.scanType+'条码内容：' + res.result);
						this.scanValue = res.result
					}
				});
			},
			dialogToggle(type) {
				this.msgType = type
				this.$refs.alertDialog.open()
			},
			confirmBtn() {
				this.$refs.alertDialog.close()
				uni.redirectTo({
					url: '../index/index2'  //这是你的当前页面地址
				 });
			},
			//设置时间
			async submit(item) {
				const res=await addConfig({serialNumber:'88888888',powerOnTime:item.powerOnTime,powerOutageTime:item.powerOutageTime})
				this.dialogToggle('info')
				return
				// if (!this.scanValue) {
				// 	uni.showToast({
				// 		icon: "none",
				// 		title: "请先扫描产品设备码",
				// 		duration: 3000,
				// 	})
				// 	return
				// }
				// this.openBluetoothAdapter()
			},
			//蓝牙初始化
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: e => {
						console.log('初始化蓝牙成功:' + e.errMsg);
						this.onBluetoothDeviceFound()
						return
						//获取本机蓝牙适配器状态。
						uni.getBluetoothAdapterState({
							success: function(res) {
								// 初始化完毕开始搜索
								if (res.available) {
									if (res.discovering) {
										// console.log('停止连接');
										this.closeBluetooth()
									}
									uni.startBluetoothDevicesDiscovery({
										success: res => {},
										fail: res => {
											onsole.log("查找设备失败!");
											uni.showToast({
												icon: "none",
												title: "查找设备失败！",
												duration: 3000,
											})
										}
									})
								} else {
									console.log('本机蓝牙不可用')
									uni.showToast({
										title: "本机蓝牙不可用！",
										duration: 3000,
									})
								}
							}
						})
					},
					fail: e => {
						if (e.errCode == 10001) {
							uni.showModal({
								title: "提示",
								content: "您的蓝牙没有打开，请打开蓝牙",
								success: function(res) {
									if (res.confirm == true) {
										if (uni.getSystemInfoSync().platform == 'ios') {} else if (
											uni.getSystemInfoSync().platform ===
											'android') {}
									} else {
										// uni.navigateBack({
										// 	url: '../../detail3/detail3'
										// })
									}
								},
							});
						}
						console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
					}
				});
			},


			//发现外围设备
			onBluetoothDeviceFound() {
				//监听寻找设备
				uni.onBluetoothDeviceFound(devices => {
					console.log('开始监听寻找到新设备的事件',devices);
					this.getBluetoothDevices();
				});
			},
			//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			getBluetoothDevices() {
				// uni.showLoading({
				// 	title: '获取蓝牙设备中...'
				// });
				uni.getBluetoothDevices({
					success: res => {
						console.log(res)
						this.resdic = res
						for (let i = 0; i < this.resdic.devices.length; i++) {
							let devicesDic = this.resdic.devices[i];
							//"S2247bb4a4cba05c3C","E07","IS31-BLE","Xiaomi Smart Band 7 7C44"
							/* if (devicesDic.name && devicesDic.name == "Xiaomi Smart Band 7 7C44" && devicesDic
								.advertisServiceUUIDs) {
								this.deviceIdStr = devicesDic.deviceId
								this.stopBluetooth()
								this.createBLEConnection(devicesDic.deviceId)
							} */
							if (devicesDic.name && devicesDic.advertisServiceUUIDs) {
								// uni.hideLoading();
								console.log(devicesDic, 'devicesDic')
								this.deviceIdStr = devicesDic.deviceId
								// this.stopBluetooth()
								this.createBLEConnection(devicesDic.deviceId)
							}
						}
					},
					fail: (err) => {
						// uni.hideLoading();
					}
				});
			},

			//连接低功耗蓝牙设备。
			createBLEConnection(deviceIds) {
				console.log("连接蓝牙---------------" + deviceIds)
				// uni.showLoading({
				// 	title: '连接蓝牙中...'
				// });
				uni.createBLEConnection({
					deviceId: deviceIds.toString(),
					success: (res) => {
						// uni.hideLoading();
						console.log('蓝牙连接成功');
						// this.stopBluetooth()
						// var that = this
						uni.getSystemInfo({
							success: (res) => {
								if (res.platform == 'ios') {
									setTimeout(() => {
										this.getBLEDeviceServices(deviceIds)
									}, 2000)
								} else {
									setTimeout(() => {
										this.nogetBLEDeviceServices(deviceIds)
									}, 3000)
								}
							},
							fail(res) {
								console.log(777777777777777)
							}
						})
					},
					fail: (res) => {
						// uni.hideLoading();
						console.log('蓝牙连接失败：' + res.errCode)
						this.closeBluetooth();
						this.createBLEConnection(deviceIds)
					},

				});

			},

			//iOS端获取Servicesid
			async getBLEDeviceServices(deviceIds) {

				var that = this

				let deviceServices = await uni.getBLEDeviceServices({

					deviceId: deviceIds

				})

				if (deviceServices[0] == null) {
					let services = deviceServices[1].services
					if (services.length == 0) {
						setTimeout(() => {
							that.getBLEDeviceServices(deviceIds)
						}, 1500)
					} else {
						console.log(services, 88888888888)
						for (let i = 0; i < services.length; i++) {
							let serviceId = services[i].uuid
							// console.log('serviceId====' + serviceId);
							let characteristicsDic = await uni.getBLEDeviceCharacteristics({
									deviceId: deviceIds,
									serviceId: serviceId,
								})
								.then(data => {
									// console.log(JSON.stringify(data))
									if (data[0] == null) {
										let characteristicsArr = data[1].characteristics
										let properties = characteristicsArr[0].properties
										console.log(properties)
										if (properties.write == true) {
											that.serviceIdStr = serviceId;
											that.characteristicsIdStr = data[1].characteristics[0].uuid;
											that.notifyBLECharacteristicValueChange(that.characteristicsIdStr)
											that.writeBLECharacteristic(deviceIds, serviceId, that
												.characteristicsIdStr)
										} else {
											console.log('不可编辑', data[1].characteristics[0].uuid)
										}
									}
								})
						}
					}
				} else {
					uni.showModal({
						title: "提示",
						content: "获取设备服务信息失败，请重新获取",
						showCancel: false,
						success(res) {

						}
					})
				}
			},

			//安卓获取Servicesid
			nogetBLEDeviceServices(deviceIds) {
				var that = this
				uni.getBLEDeviceServices({
					deviceId: deviceIds,
					success(res) {
						let services = res.services
						console.log(services, 55555)
						if (services.length == 0) {
							setTimeout(() => {
								that.nogetBLEDeviceServices(deviceIds)
							}, 3000)
						} else {
							console.log(66666)
							for (let i = 0; i < services.length; i++) {
								let serviceId = services[i].uuid
								//这个比对serviceId，设备厂家会告诉，因为安卓获取特征值都是不可写入的，iOS 的可以写入的，所以安卓直接判断serviceId是不是厂家发的serviceId
								if (serviceId) {
									uni.getBLEDeviceCharacteristics({
										deviceId: deviceIds,
										serviceId: serviceId,
										success(result) {
											let propertiesDic = result.characteristics[0]
											console.log(propertiesDic, 77777)
											that.serviceIdStr = serviceId;
											that.characteristicsIdStr = propertiesDic.uuid;
											that.notifyBLECharacteristicValueChange(that
												.characteristicsIdStr)
											setTimeout(() => {
												that.writeBLECharacteristic(deviceIds, serviceId,
													that.characteristicsIdStr)
											}, 2000)
										},
										fail(result) {
											console.log(result, 2222222)
										}
									})
								}
							}
						}
					},
					fail(res) {
						console.log(res, 8888888)
					}
				})
			},


			//监听设备返回的值
			notifyBLECharacteristicValueChange(characteristicId) {
				console.log(characteristicId, 'characteristicId')
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: this.deviceIdStr,
					serviceId: this.serviceIdStr,
					characteristicId: this.characteristicsIdStr,
					success: (res) => {
						// console.log(this.characteristicId)
						console.log('notifyBLECharacteristicValueChange success', res)
						this.onBLECharacteristicValue()
					},
					fail: (res) => {
						console.log('notifyBLECharacteristicValueChange fail', res)
					}
				})
			},

			//根据设备上返回的数据，进行筛选
			onBLECharacteristicValue() {
				var that = this
				uni.onBLECharacteristicValueChange(function(res) {
					// console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
					const resultStr = hexCharCodeToStr(ab2hex(res.value))
					// let resultStr = that.bufferString(res.value)
					// console.log(resultStr,111)
					if (resultStr && resultStr != '') {
						//resultStr就是设备上返回的数据，根据设备不同，获取的设备格式也就不同，自己筛选吧
					}

				})

			},

			//向蓝牙设备发送指令
			writeBLECharacteristic(deviceId, serviceId, characteristicId) {
				var that = this
				let sgInt = stringTobuffer('>sAg>')
				// console.log(sgInt.byteLength)
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceIdStr,
					serviceId: that.serviceIdStr,
					characteristicId: that.characteristicsIdStr,
					value: sgInt,
					success: function(res) {
						console.log(typeof(res))
						console.log('writeBLECharacteristicValue success', res.errMsg, sgInt)
						// that.closeBluetooth()
					},
					fail: function(res) {
						console.log(typeof(res))
						console.log('writeBLECharacteristicValue fail==', res.errCode, res.errMsg)
					}
				})
			},


			//停止搜索蓝牙设备
			stopBluetooth() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					},
					fail: e => {
						console.log('停止搜索蓝牙设备失败，错误码：' + e.errCode);
					}
				});
			},

			//关闭蓝牙模块
			closeBluetooth() {

				uni.closeBluetoothAdapter({

					success(res) {

						console.log(res)

					}

				})

			},
		}
	}
</script>

<style lang="less" scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.top {
		width: 100%;
		height: 382rpx;
		background: url('../../static/images/beijingse.png') center bottom no-repeat;
		background-size: cover;
		position: relative;

		.text {
			margin-left: 60rpx;

			.title {
				font-size: 40rpx;
				line-height: 52rpx;
				color: rgb(253, 253, 254);
				font-weight: 700;
				display: block;
				margin-top: 112rpx;
				margin-bottom: 6rpx;
			}

			.title-en {
				font-size: 18rpx;
				line-height: 24rpx;
				color: rgb(253, 253, 254);
				opacity: 0.3;
				display: block;
				margin-bottom: 40rpx;
			}

			image {
				width: 48rpx;
				height: 12rpx;
			}
		}

		.position-img {
			position: absolute;
			top: 70%;
			transform: translateY(-50%);
			right: 60rpx;
			width: 282rpx;
			height: 270rpx;
		}
	}

	.scancode-box {
		position: relative;
		z-index: 2;
		width: calc(100% - 60rpx);
		margin: -94rpx auto 0;

		.scancode {
			position: relative;
			padding: 32rpx;
			border-radius: 20rpx;
			background: rgba(253, 253, 254, 0.5);
			box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
			backdrop-filter: blur(36rpx);
			border: 1rpx solid rgb(234, 234, 234);

			.scancodetitle {
				font-weight: 700;
				font-size: 32rpx;
				line-height: 46rpx;
				margin-bottom: 32rpx;
				color: #333333;
			}

			.scan-input {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.uni-input {
					width: 498rpx;
					height: 88rpx;
					border-radius: 12rpx;
					background-color: rgb(253, 253, 254);
					border: 1px solid rgb(234, 234, 234);
					line-height: 38rpx;
					font-size: 26rpx;
					padding: 0 0 0 32rpx;

					:-moz-placeholder {
						font-size: 26rpx;
						line-height: 38rpx;
						color: #999999;
					}
				}

				/deep/.scan-icon {
					.uniui-scan {
						font-size: 80rpx !important;
					}
				}
			}
		}
	}

	.time-box {
		margin-top: 32rpx;
		width: calc(100% - 60rpx);

		.setting-box {
			position: relative;
			padding: 32rpx;
			border-radius: 20rpx;
			background: rgba(253, 253, 254, 0.5);
			box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
			border: 1rpx solid rgb(234, 234, 234);

			.time-title {
				font-weight: 700;
				font-size: 32rpx;
				line-height: 46rpx;
				margin-bottom: 32rpx;
				color: #333333;
			}

			.setting-time {
				display: flex;
				justify-content: space-between;

				/deep/.uni-forms {
					flex: 0 0 calc(100% - 192rpx);
					width: calc(100% - 192rpx);

					.uni-forms-item {
						align-items: center;
						margin-bottom: 20rpx;

						&:last-child {
							margin-bottom: 0;
						}
					}

					.uni-forms-item__label {
						width: 140rpx !important;
						font-size: 26rpx;
					}

					.uni-forms-item__content {
						background-color: rgb(238, 238, 238);
						width: 292rpx;
						height: 88rpx;
						line-height: 88rpx;
						border-radius: 6px;
						text-align: center;
					}
				}

				.submit-btn {
					width: 172rpx;
					flex: 0 0 172rpx;
					height: 196rpx;
					border-radius: 12rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}
		}
	}

	.history-box {

		margin: 32rpx 0;
		width: calc(100% - 60rpx);

		.setting-history {
			padding: 32rpx;
			border-radius: 20rpx;
			background: rgb(238, 238, 238);
			border: 1rpx solid rgb(234, 234, 234);
			min-height: 592rpx;

			.history-title {
				display: flex;
				justify-content: space-between;
				margin-bottom: 32rpx;

				.min-title {
					font-weight: 400;
					font-size: 26rpx;
					line-height: 38rpx;
					color: #666666;
				}

				.click {
					color: #999999;
					font-weight: 400;
					font-size: 26rpx;
					line-height: 38rpx;
				}
			}

			.empty {
				height: 520rpx;
				justify-content: center;
				display: flex;
				align-items: center;

				image {
					width: 428rpx;
					height: 300rpx;
				}
			}

			.history-list {
				height: 520rpx;

				ul {
					li {
						display: flex;
						justify-content: space-between;
						height: 88rpx;
						margin-bottom: 20rpx;
						align-items: center;

						&:last-child {
							margin-bottom: 0;
						}

						.sort {
							font-weight: 400;
							font-size: 26rpx;
							line-height: 38rpx;
							color: #666666;
						}

						.bluetooth-item {
							background-color: rgb(253, 253, 254);
							padding: 24rpx 28rpx;
							flex: 0 0 500rpx;
							width: 500rpx;
							border-radius: 12rpx;
							border: 2rpx solid rgb(234, 234, 234);
							display: flex;
							align-items: center;
							justify-content: space-between;

							text {
								font-weight: 400;
								font-size: 26rpx;
								line-height: 38rpx;
								color: #666666;
							}

							image {
								width: 40rpx;
								height: 40rpx;
							}
						}
					}
				}
			}
		}
	}

	.popup-content {
		background-color: #fff;
		width: 556rpx;
		height: 368rpx;
		border-radius: 20rpx;
		text-align: center;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;

		.img {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			top: -115rpx;
			width: 282rpx;
			height: 270rpx;
		}

		.text {
			font-weight: 700;
			font-size: 30rpx;
			line-height: 44rpx;
			color: #333333;
		}

		.confirm-btn {
			position: absolute;
			width: 100%;
			left: 0%;
			bottom: 0;
			background-color: rgb(48, 92, 255);
			color: #fff;
			font-weight: 700;
			font-size: 30rpx;
			line-height: 44rpx;
			padding: 24rpx 0 22rpx 0;
			border-radius: 0 0 20rpx 20rpx;
		}
	}
</style>